<?php

namespace backend\modules\translation;

use backend\modules\translation\models\Source;
use backend\modules\translation\models\Translation;
use common\base\MultiModel;
use yii\helpers\Json;

//http://fy.iciba.com/ajax.php?a=fy&f=en&t=zh&w=timeline
/**
 * translation module definition class
 */
class Module extends \yii\base\Module
{
    /** @inheritdoc */
    public $controllerNamespace = 'backend\modules\translation\controllers';

    /**
     * @param \yii\i18n\MissingTranslationEvent $event
     */
    public static function missingTranslation($event)
    {
        //自动添加没有翻译的
        $source =   Source::findOne(['category'=>$event->category,'message'=>$event->message]);
        if($source ==null){
            $source = new Source();
            $source->category=$event->category;
            $source->message=$event->message;
            $source->save();

            $message = new Translation();
            $message->id = $source->id;
            $message->language='zh';
            $message->translation = self::getTranslate($event->message);
            $message->save();

        }else{

            $message = Translation::findOne(['id'=>$source->id,'language'=>'zh']);
            if($message == null){
                $nmessage = new Translation();
                $nmessage->id = $source->id;
                $nmessage->language='zh';
                $nmessage->translation = self::getTranslate($event->message);
                $nmessage->save();
            }
        }

    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        // custom initialization code goes here
    }
   static public function getTranslate($word){

    //    $url ="http://fy.iciba.com/ajax.php?a=fy&f=en&t=zh&w=$word";
    //     $json = file_get_contents($url);
    //     $data = Json::decode($json);

    //     if( isset($data['content']['word_mean'][0])   ){
    //         if(strpos($data['content']['word_mean'][0],';') != null){
    //             return strstr($data['content']['word_mean'][0],';',true);
    //         }else{
    //             return $data['content']['word_mean'][0];
    //         }

    //     }else{
    //         return '';
    //     }
        return '';

    }
}
